import React, { useEffect, useRef, useState } from 'react';
import { message } from 'antd';
import { GForm } from 'geminis-react';
import * as CryptoJS from 'crypto-js';
import './index.less';

export default () => {
  const [siteInfo, setSiteInfo] = useState<any>();
  const form = useRef<any>();

  const schema = {
    data: {
      url: '/api/auth/login',
      format: 'form',
    },
    layout: {
      layout: 'vertical',
      size: 'large',
      wrapperCol: 24,
      submit: {
        text: '登录',
        'x-component-props': {
          block: 'block',
          size: 'large',
        },
      },
    },
    fields: {
      type: 'object',
      properties: {
        username: {
          type: 'string',
          title: '',
          required: true,
          'x-decorator': 'FormItem',
          'x-component': 'Input',
          'x-component-props': {
            placeholder: '请输入用户名',
            prefix: '{{icon(\'icon-user\')}}',
          },
        },
        password: {
          type: 'string',
          title: '',
          required: true,
          'x-decorator': 'FormItem',
          'x-component': 'Password',
          'x-component-props': {
            placeholder: '请输入密码',
            prefix: '{{icon(\'icon-password\')}}',
          },
        },
      },
    },
  };

  const onSubmitted = (data: any, resp: any) => {
    if (data.status === 302) {
      message.success('登录成功，正在进入系统...');
      window.location = data.location;
    } else {
      message.error(data.msg);
    }
  };

  const onSubmitting = (value: any): void => {
    value.password = CryptoJS.SHA256(value.password).toString();
  };

  useEffect(() => {
    // request
    //   .get('/config/config.json')
    //   .then((resp) => {
    //     setSiteInfo(resp);
    //   })
    //   .catch((err) => {
    //     message.error('获取配置错误');
    //     console.log(err);
    //   });
    window.onkeyup = (event)=>{
      if(event.key === 'Enter'){
        form.current.submit();
      }
    }
  }, []);

  return (
    <div id="login">
      <div id="center">
        <div id="title">{siteInfo?.title}</div>
        <GForm ref={form} schema={schema} onSubmitting={onSubmitting} onSubmitted={onSubmitted} />
      </div>
    </div>
  );
};
